import axios from 'axios';
import { randomFill } from 'crypto';
export default {
	data() {
		return {
			modalData: {
				modalName: '',
				itemId: '' //每条数据所在行的id
			},
			wechatMsg: {}, //绑定成功之后显示的信息
			itemData: {
				nickName: '',
				role: 0,
				telephone: '',
				userId: '',
				password: ''
			},
			rules: {
				nickName: [
					{
						required: true,
						message: '请输入用户昵称',
						trigger: 'blur'
					},
					{
						min: 2,
						max: 30,
						message: '长度在 2 到 30 个字符',
						trigger: 'change'
					}
				],
				telephone: [
					{
						required: true,
						message: '请输入手机号码',
						trigger: 'blur'
					},
					{
						validator(r, v, b) {
							/^1\d{10}$/.test(v) ? b() : b(new Error('手机格式不符合'));
						}
					}
				],
				userId: [
					{
						required: true,
						message: '请输入帐号',
						trigger: 'blur'
					}
				],
				password: [
					{
						required: true,
						message: '请输入密码',
						trigger: 'blur'
					}
				]
			},
			headimgurl: '',
			socketTimer: null,
			socket: null
		};
	},
	methods: {
		getList() {
			this.getRoleList(this.searchParams);
		},
		//查询列表
		getRoleList(aparams) {
			let self = this,
				params = {
					pageNumber: this.pageNumber,
					pageSize: this.pageSize,
					sortType: 'ASC'
				};
			params = $.extend({}, params, aparams);
			self.tbodysInfo = [];
			axios
				.post('/zbcloud/user-service/sentryUser/getAll', params)
				.then(res => {
					let list = res.data.list;
					self.tbodysInfo = list ? list : [];
					self.total = res.data.total;
				})
				.catch(error => {
					console.log(error);
				});
		},
		handle(rowData, type) {
			switch (type) {
				case 'bindPark':
					this._bindPark('设定权限', rowData);
					break;
				case 'edit':
					this._add(rowData);
					break;
				case 'isBind':
					this._isBind(rowData);
					break;
				case 'isUp':
					this._isUp(rowData);
					break;
				case 'del':
					this._del(rowData.id);
					break;
				default:
					break;
			}
		},
		_isUp(rowData) {
			let self = this;
			if (rowData.enable) {
				axios
					.get('/zbcloud/user-service/sentryUser/freeze/' + rowData.id)
					.then(res => {
						self.showToast('冻结成功', 1);
						self.getList();
					})
					.catch(error => {
						console.log(error);
					});
			} else {
				axios
					.get('/zbcloud/user-service/sentryUser/unfreeze/' + rowData.id)
					.then(res => {
						self.showToast('启用成功', 1);
						self.getList();
					})
					.catch(error => {
						console.log(error);
					});
			}
		},
		_isBind(rowData) {
			console.log(rowData);
			let _this = this;
			if (rowData.wexinId) {
				_this.modalData.modalName = '解绑微信';
				_this.modalData.itemId = rowData.id;
				axios
					.get('/zbcloud/user-service/sentryUser/getHeadUrl/' + rowData.id)
					.then(res => {
						console.log(res);
						_this.headimgurl = res.data ? res.data : '';
						_this.wechatMsg.headimgurl = res.data ? res.data : '';
						_this.toOpenModal('unbindModal');
					})
					.catch(error => {
						console.log(error);
					});
			} else {
				_this.modalData.modalName = '绑定微信';
				_this.wechatMsg = {};
				axios
					.post('/zbcloud/user-service/sentryUser/getQRCodeUrl', {
						id: rowData.id,
						sessionId: _this.getRandom(9)
					})
					.then(res => {
						_this.QRCode = res.data ? res.data : '';
						_this.toOpenModal('bindModal');
						_this.openSocket();
					})
					.catch(error => {
						console.log(error);
					});
			}
		},
		unbind() {
			let _this = this;
			axios
				.get('/zbcloud/user-service/sentryUser/untieWeiXin/' + _this.modalData.itemId)
				.then(res => {
					_this.showToast('解绑成功', 1);
					_this.getList();
					_this.closed('unbindModal');
				})
				.catch(error => {
					console.log(error);
				});
		},
		getRandom(num) {
			return Math.floor((Math.random() + Math.floor(Math.random() * 9 + 1)) * Math.pow(10, num - 1));
		},
		openSocket() {
			if (this.socket) {
				this.socket.close();
			}
			let self = this;
			let randomNum = self.getRandom(9);
			this.socket = new WebSocket(window.YDT_CLOUD_URI + '/websocket104?sessionId=' + randomNum);

			this.socket.onopen = function(res) {
				console.log(res);
			};

			this.socket.onmessage = function(event) {
				let res = JSON.parse(event.data);
				console.log(res);
				if (res.code === 400) {
					self.showToast(res.msg, 2, 2500);
				}
				if (res.code === 0) {
					self.wechatMsg = {
						nickname: res.nickname,
						headimgurl: res.headimgurl
					};
					self.socket.close();
					self.getList();
					setTimeout(() => {
						self.closed('bindModal');
						self.showToast('绑定微信成功', 1);
					}, 2000);
				}
			};

			this.socket.onclose = () => {
				console.log('socket close');
			};

			this.socket.onerror = () => {
				self.socketTimer = setTimeout(() => {
					self.openSocket();
				}, 2000);
			};
		},
		cancleBindWechat() {
			this.closed('bindModal');
		},
		//打开新增
		_add(row) {
			if (row) {
				this.modalData.modalName = '编辑用户';
				this.itemData = {
					nickName: row.nickName,
					role: row.role.toString(),
					telephone: row.telephone,
					id: row.id,
					userId: row.userId,
					password: row.password
				};
			} else {
				this.modalData.modalName = '新增用户';
				this.itemData = {
					nickName: '',
					role: '0',
					telephone: '',
					id: null,
					userId: '',
					password: ''
				};
			}
			this.toOpenModal('itemModal');
		},
		_save(formName) {
			let self = this;

			let url = self.itemData.id
				? '/zbcloud/user-service/sentryUser/update'
				: '/zbcloud/user-service/sentryUser/add';

			this.$refs[formName].validate(valid => {
				if (valid) {
					let params = Object.assign(this.itemData, {
						password: this.itemData.password
					});
					axios
						.post(url, params)
						.then(res => {
							if (res.data.status == 0) {
								self.showToast('操作成功', 1);
								self.closed('itemModal');
								self.getList();
							} else {
								self.showToast('操作失败', 2);
							}
						})
						.catch(error => {
							console.log(error);
						});
				} else {
					return false;
				}
			});
		},
		_del(id) {
			let self = this;
			this.showDialog(
				'是否确认删除所选记录？',
				[],
				function() {
					axios
						.delete('/zbcloud/user-service/sentryUser/' + id)
						.then(res => {
							if (res.data.status == 0) {
								self.showToast('操作成功', 1);
								self.getList();
							} else {
								self.showToast('操作失败', 2);
							}
						})
						.catch(error => {
							console.log(error);
						});
				},
				'温馨提示',
				function() {
					//取消时不操作
				}
			);
		},
		_bindPark(modalName, row) {
			console.log(row);
			let self = this;
			let params = {
				id: row.id
			};
			// let chkStyle = row.role === 0 ? 'radio' : 'checkbox'
			let settings = {
				check: {
					enable: true,
					chkStyle: 'checkbox',
					radioType: 'all'
				},
				data: {
					simpleData: {
						enable: true
					}
				},
				view: {
					showIcon: false,
					showLine: false
				}
			};
			this.modalData.modalName = modalName;
			this.modalData.itemId = row.id;
			this.toOpenModal('setPrivilegeModal', 1);
			axios
				.get('/zbcloud/user-service/sentryUser/getParkInfo/', {
					params: params
				})
				.then(res => {
					let type = self.modalData.modalName.indexOf('查看权限') != -1;
					if (res.status && res.data) {
						res.data.forEach(element => {
							//父节点无选项框
							if (element.isParent) {
								element.nocheck = true;
							}
							//默认选中节点框
							if (element.selectd) {
								element.checked = true;
							}
							//查看时不允许更改权限
							if (type) {
								element.chkDisabled = true;
							}
						});
						console.log(res.data);
						let treeObj = $.fn.zTree.init($('#privilegeTree'), settings, res.data);
						treeObj.expandAll(true);
					}
				})
				.catch(error => {
					console.log(error);
				});
		},
		forceoffwork(item) {
			let _this = this;
			let params = {
				user_id: item.id,
				operator: ''
			};
			let _userInfo = sessionStorage.getItem('userInfo');
			if (_userInfo) {
				let userInfo = JSON.parse(_userInfo);
				params.operator = userInfo.loginid;
			}
			axios
				.post('/zbcloud/user-service/sentryUser/forceOfDuty', params)
				.then(res => {
					_this.showToast('操作成功', 1);
					_this.getList();
				})
				.catch(error => {
					console.log(error);
				});
		},
		//保存权限
		SetPrivilege() {
			var self = this;
			var tree = $.fn.zTree.getZTreeObj('privilegeTree');
			var nodes = tree.getCheckedNodes(true);
			var parkIdArr = [];
			if (nodes.length > 0) {
				nodes.forEach(element => {
					parkIdArr.push(element.id);
				});
			}
			console.log(self.itemId, parkIdArr);
			axios
				.post('/zbcloud/user-service/sentryUser/bindUserPark/' + self.modalData.itemId, parkIdArr)
				.then(res => {
					if (res.data.status == 0) {
						self.showToast('操作成功', 1);
						self.closed('setPrivilegeModal');
					} else {
						self.showToast('操作失败', 2);
					}
				})
				.catch(error => {
					console.log(error);
				});
		},
		//必须定义获取多列的方法
		filterMultiCheck(selectionArr) {
			let result = [];
			selectionArr.map(item => {
				result.push(item.id);
			});
			return result;
		}
	}
};
